package com.database.service.impl;


import com.database.character.Collect;
import com.database.character.Post;
import com.database.character.UserAccount;
import com.database.mapper.CollectMapper;
import com.database.mapper.PostMapper;
import com.database.mapper.UserMapper;
import com.database.service.CollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CollectServiceImpl implements CollectService {

  @Autowired
  private PostMapper postMapper;

  @Autowired
  private UserMapper userMapper;

  @Autowired
  private CollectMapper collectMapper;

  @Override
  public void addCollect(Collect collect) {
    Integer userId = collect.getUserId();
    Integer postId = collect.getPostId();
    UserAccount userAccount = userMapper.getByUid(userId);
    Post post = postMapper.getPostByPid(postId);
    userAccount.setCollectNum(userAccount.getCollectNum() + 1);//该用户收藏数加一
    post.setCollectNum(post.getCollectNum() + 1);//该帖子收藏数加一
    userAccount.setUpdateTime(LocalDateTime.now());//用户更新时间
    post.setUpdateTime(LocalDateTime.now());//帖子更新时间
    userMapper.updateUser(userAccount);
    postMapper.updatePost(post);
    collectMapper.addCollect(collect);
  }

  @Override
  public void deleteCollectByPostId(Integer postId) {
    Post post = postMapper.getPostByPid(postId);
    post.setCollectNum(post.getCollectNum() - 1);//该帖子收藏数减一
    post.setUpdateTime(LocalDateTime.now());//帖子更新时间
    postMapper.updatePost(post);
    Collect collect = collectMapper.getCollectByPid(postId);
    Integer userId = collect.getUserId();
    UserAccount userAccount = userMapper.getByUid(userId);
    userAccount.setCollectNum(userAccount.getCollectNum() - 1);//该用户收藏数减一
    userAccount.setUpdateTime(LocalDateTime.now());//用户更新时间
    userMapper.updateUser(userAccount);
    collectMapper.deleteCollectByPostId(postId);
  }

  @Override
  public List<Collect> getCollectByUid(Integer userId) {
    return collectMapper.getCollectByUid(userId);
  }
}
